package com.lagou.edu.mvcframework.interceptor;

import com.lagou.edu.mvcframework.constants.RequestAttributes;
import com.lagou.edu.mvcframework.context.PermissionContext;
import com.lagou.edu.mvcframework.pojo.Invoker;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
 * @author liuc
 * @date 2021/4/22
 * @description 权限校验的默认实现
 **/
public class DefaultPermissionInterceptor extends PermissionInterceptor{

    @Override
    protected boolean hasPermission(HttpServletRequest request, HttpServletResponse response) {
        //获取上游方法放置的参数
        String[] controllerUsers = (String[])request.getAttribute(RequestAttributes.HANDLER_CONTROLLER_USER);
        String[] methodUsers = (String[])request.getAttribute(RequestAttributes.HANDLER_METHOD_USER);
        String username = PermissionContext.getUsername();
        //先判断method上的注解是否匹配
        if(methodUsers != null && methodUsers.length != 0){
            if(Arrays.asList(methodUsers).contains(username)){
                return true;
            }
            //不为空表示没有匹配上,强校验返回false
            return false;
        }
        //后判断controller上的注解是否匹配
        if(controllerUsers != null && controllerUsers.length != 0){
            if(Arrays.asList(controllerUsers).contains(username)){
                return true;
            }
            return false;
        }else{
            //为空表示不需要权限即可访问
            return true;
        }
    }
}
